import React, { Component } from 'react';
import { observable } from 'mobx';
import { observer, inject } from "mobx-react";
import {
  Table, Input, Button, Form, Pagination, Modal, message
} from 'antd';
import moment from 'moment';
import ChooseTips from '@/components/ChooseTips/ChooseTips'
import http from '../../../../../common/http';
import './EditTable.less'

const FormItem = Form.Item;
const EditableContext = React.createContext();
const confirm = Modal.confirm;

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends Component {
  state = {
    editing: false,
  }

  componentDidMount() {
    if (this.props.editable) {
      document.addEventListener('click', this.handleClickOutside, true);
    }
  }

  componentWillUnmount() {
    if (this.props.editable) {
      document.removeEventListener('click', this.handleClickOutside, true);
    }
  }

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  }

  handleClickOutside = (e) => {
    const { editing } = this.state;
    if (editing && this.cell !== e.target && !this.cell.contains(e.target)) {
      this.save();
    }
  }

  save = () => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  }

  render() {
    const { editing } = this.state;
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      ...restProps
    } = this.props;
    return (
      <td ref={node => (this.cell = node)} {...restProps}>
        {editable ? (
          <EditableContext.Consumer>
            {(form) => {
              this.form = form;
              return (
                editing ? (
                  <FormItem style={{ margin: 0 }}>
                    {form.getFieldDecorator(dataIndex, {
                      rules: [{
                        required: true,
                        message: `${title} is required.`,
                      }],
                      initialValue: record[dataIndex],
                    })(
                      <Input
                        ref={node => (this.input = node)}
                        onPressEnter={this.save}
                      />
                    )}
                  </FormItem>
                ) : (
                  <div
                    className="editable-cell-value-wrap"
                    style={{ paddingRight: 24 }}
                    onClick={this.toggleEdit}
                  >
                    {restProps.children}
                  </div>
                )
              );
            }}
          </EditableContext.Consumer>
        ) : restProps.children}
      </td>
    );
  }
}

@inject('rootStore') @observer
class EditTable extends Component {
  @observable showCreateCategoryModal = false;
  @observable showCreateRepeat = false;
  @observable createCategoryParam = {
    "desc": "",
    "id": 0,
    "local": "en",
    "name": "",
    "parentId": 0,
    "sort": 0
  }
  @observable selectedRowsLength = 0;
  @observable selectedRowKeys = []

  componentDidMount() {
    const newsStore = this.props.rootStore.newsStore;
    newsStore.toGetNewsCategory('en');
  }

  constructor(props) {
    super(props);
    this.columns = [{
      title: 'Category',
      dataIndex: 'name',
      width: '30%',
      editable: true,
    }, {
      title: 'Sort',
      dataIndex: 'sort',
      editable: true,
    }, {
      title: 'CreateTime',
      render: (text, record) => (
        <div>{moment(record.gmtCreate).format('YYYY-MM-DD MM:ss')}</div>
      )
    }, {
      title: 'Operation',
      dataIndex: 'operation',
      render: (text, record) => (
        <div className="edit-config">
          <span className="edit-text" onClick={() => this.showDeleteConfirm(record.id, props)}>Delete</span>
        </div>
      ),
    }];
  }

  createCategoryValueOnChange = (e) => {
    this.createCategoryParam.name = e.target.value;
  }

  handleSave = (row) => {
    const newsStore = this.props.rootStore.newsStore;
    http.post('/news/category/update', row)
    .then((response) => {
      if (response.success) {
        newsStore.toGetNewsCategory('en');
      }
    })
  }

  openCreateModal = () => {
    this.showCreateCategoryModal = true
  }

  confirmCreateModal = () => {
    const newsStore = this.props.rootStore.newsStore;
    if (this.createCategoryParam.name !== '') {
      http.post('/news/category/insert', this.createCategoryParam)
      .then((response) => {
        if (response.success) {
          this.closeCreateModal();
          newsStore.toGetNewsCategory('en');
          message.success('Success');
        } else {
          if (response.message === 'name_unique_index') {
            this.showCreateRepeat = true
          }
        }
      })
    } else {
      message.warning('Category Name Can Not Be Null');
    }

  }

  closeCreateModal = () => {
    this.createCategoryParam.name = '';
    this.showCreateCategoryModal = false;
    this.showCreateRepeat = false;
  }

  clearChooseTips = () => {
    this.selectedRowKeys = []
    this.selectedRowsLength = 0;
  }

  clearSelectRows = () => {
    this.selectedRowKeys = [];
    this.selectedRowsLength = 0;
  }

  showDeleteConfirm = (id, props) => {
    const that = this
    confirm({
      title: 'Are you sure delete this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const newsStore = props.rootStore.newsStore;
        newsStore.toDeleteCategory(id);
        that.clearSelectRows();
      },
      onCancel() {
      },
    });
  }

  batchDelete = (that, props) => {
    if (this.selectedRowKeys.length !== 0) {
      confirm({
        title: 'Are you sure delete this news?',
        content: 'You can reapprove it in unavailable list',
        okText: 'Confirm',
        cancelText: 'Cancel',
        centered: true,
        onOk() {
          const newsStore = props.rootStore.newsStore;
          newsStore.toBatchDeleteCategory(that.selectedRowKeys.join());
          that.clearSelectRows();
        },
        onCancel() {
        },
      });
    } else {
      message.warning('Please select at least one');
    }
  }

  render() {
    const selectedRowKeys = this.selectedRowKeys;
    const newsStore = this.props.rootStore.newsStore;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });

    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRowsLength  = selectedRows.length;
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };

    return (
      <div className="edit-table">
        <div className="config-btn-group">
          <Button
            type="primary"
            className="config-btn"
            onClick={this.openCreateModal}>+ Create</Button>
          <Button
            type="primary"
            onClick={() => this.batchDelete(this, this.props)}>Batch Delete</Button>
        </div>
        <ChooseTips
          tipsNumber={this.selectedRowsLength}
          clearChooseTips={this.clearChooseTips} />
        <Table
          rowKey="id"
          className="mt10"
          components={components}
          rowSelection={rowSelection}
          rowClassName={() => 'editable-row'}
          dataSource={newsStore.categoryList}
          columns={columns}
          pagination={false}
        />
        <Pagination
          className="tr mt10"
          showQuickJumper
          showSizeChanger
          showTotal={total => `Total ${total}`}
          total={newsStore.categoryListTotal}
          onChange={newsStore.toChangeCategoryPageNumber}
          onShowSizeChange={(current, pageSize) => newsStore.toChangeCategoryPageSize(pageSize)}
          current={newsStore.categoryParam.pageIndex}
        />
        <Modal
          title="Create"
          visible={this.showCreateCategoryModal}
          onOk={this.confirmCreateModal}
          onCancel={this.closeCreateModal}
          centered>
          <div className="create-category-modal">
            <label className="msg-title">category:</label>
            <Input
              className="msg-item"
              placeholder="please create a new category"
              value={this.createCategoryParam.name}
              onChange={this.createCategoryValueOnChange}/>
          </div>
          {
            this.showCreateRepeat ?
            <p className="category-tips">this category already created</p>
            :
            null
          }
        </Modal>
      </div>
    );
  }
}

export default EditTable;
